/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.trgzs.bate.modules.generator.controller;

import com.trgzs.bate.modules.generator.service.SysGeneratorService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;

/**
 * 代码生成器
 * 
 * @author Mark dong980514280@gmail.com
 */
@Controller
@RequiredArgsConstructor
@RequestMapping("/sys/generator")
public class SysGeneratorController {

	private final SysGeneratorService sysGeneratorService;

	/**
	 * 生成代码
	 */
	@PreAuthorize("@au.check('admin')")
	@RequestMapping("/code")
//	@Secured({ "admin" })
	public void code(@RequestParam(value = "moduleName") String moduleName,
					 @RequestParam(value = "author") String author,
					 @RequestParam(value = "email") String email,
					 @RequestParam("tables") String tables,
					 @RequestParam("tablePrefixes") String tablePrefixes,
					 HttpServletResponse response) throws IOException{
		// 生成代码
		byte[] data = sysGeneratorService.generatorCode(moduleName, author, email, tables.split(","), tablePrefixes.split(","));

		// 写入数据到response
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"generatorCode.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");
		IOUtils.write(data, response.getOutputStream());
	}

}
